package com.wp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wp.dao.UserDao;
import com.wp.entity.User;
import com.wp.service.UserService;
import com.wp.util.JwtUtil;
import com.wp.vo.LoginVo;
import com.wp.vo.Result;
import jdk.internal.org.objectweb.asm.Handle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: WangPeng
 * @createTime: 2022/11/22 14:23
 * @description:
 * @version: v1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public Result selectAll(int currentPage,int pageSize) {
        Page<User> page = new Page<>(currentPage, pageSize);
        Page<User> userPage = userDao.selectPage(page, null);
//        List<User> userList = userDao.selectList(null);
        return new Result(200,"查询成功",userPage);
    }

    @Override
    public Result deleteById(int id) {
        int row = userDao.deleteById(id);
        return new Result(200,"删除成功");
    }

    @Override
    public Result updateUser(User user) {
        int row = userDao.updateById(user);
        return new Result(200,"修改成功");
    }

    @Override
    public Result insertUser( User user) {
        int row = userDao.insert(user);
        return new Result(200,"添加成功");
    }

    @Override
    public Result login(LoginVo loginVo) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email",loginVo.getEmail());
        wrapper.eq("password",loginVo.getPassword());
        User user = userDao.selectOne(wrapper);
        if (user!=null){
            //生成token
            Map<String,Object> map = new HashMap<>();
            map.put("id",user.getId());
            map.put("email",user.getEmail());
            map.put("name",user.getName());
            String token = JwtUtil.createToken(map);
            return new Result(200,"登录成功",token);
        }else {
            return new Result(500, "登录失败",null);
        }
    }
}
